<template>
    <div class="generate-image-wrapper">
        <!-- <span class="warn-tip"><Icon type="ios-alert-outline" />最多可创建三个镜像</span> -->
        <template v-if="dataLoading">
            <Spin>数据加载中...</Spin>
        </template>
        <template v-else>
            <div class="flex-end" v-if="jupyterImageId">需要编程环境：<Checkbox v-model="needJupyter"></Checkbox></div>
            <div class="flex-between wp100">
                <Form
                    ref="form"
                    :model="formData"
                    :rules="rules"
                    :label-width="0"
                    inline
                    class="flex"
                    style="width: 0; flex: auto"
                >
                    <FormItem label=" " prop="imageRef" style="width: 40%" :show-message="false">
                        <Select filterable
                            v-model="formData.imageRef"
                            placeholder="镜像"
                            @on-change="changeImage"
                            filterable
                        >
                            <Option
                                v-for="(value, key) in imageList"
                                :value="value.id"
                                :key="key"
                                :title="value.imageName"
                                >{{ value.imageName }}</Option
                            >
                        </Select>
                    </FormItem>
                    <FormItem label=" " prop="flavorRef" :show-message="false" style="width: 40%">
                        <Select filterable
                            v-model="formData.flavorRef"
                            placeholder="配额"
                            @on-change="changeFlavor"
                            filterable
                        >
                            <Option
                                v-for="(value, key) in showFlavorList"
                                :value="value.id"
                                :key="key"
                                :title="value.flavorName"
                                >{{ value.flavorName }}</Option
                            >
                        </Select>
                    </FormItem>
                    <FormItem label=" " prop="count" :show-message="false" style="width: 19%">
                        <Select filterable v-model="formData.count" placeholder="数量">
                            <Option :value="1">1</Option>
                            <Option :value="2">2</Option>
                            <Option :value="3">3</Option>
                        </Select>
                    </FormItem>
                </Form>
                <Button type="primary" class="no-radius" @click="addImage()" :disabled="count >= 3"
                    >创建</Button
                >
                <WarningTip content="最多可创建三个镜像"></WarningTip>
            </div>
            <div class="image-wrapper" v-if="selectImageList.length > 0">
                <div class="image-item header flex-between">
                    <span class="text-ellipsis">镜像名称</span>
                    <span class="text-ellipsis">配额</span>
                    <span class="text-ellipsis">虚拟机个数</span>
                    <span class="text-ellipsis">操作</span>
                </div>
                <div
                    v-for="(image, index) in selectImageList"
                    :key="`${index}${image.imageRef}`"
                    class="image-item flex-between"
                >
                    <span class="text-ellipsis" :title="image.imageName">{{ image.imageName }}</span>
                    <span class="text-ellipsis" :title="image.flavorName">{{ image.flavorName }}</span>
                    <span class="text-ellipsis">{{ image.count }}</span>
                    <span
                        class="text-ellipsis"
                        @click="image.imageRef != jupyterImageId && delImage(index)"
                        :style="{color:image.imageRef === jupyterImageId ? '' : '#db4747',cursor:image.imageRef === jupyterImageId ? 'not-allowed' : 'pointer'}"
                        >删除</span
                    >
                </div>
            </div>
            <Button long type="primary" @click="templateAutomatic" v-if="selectImageList.length > 0"
                >生成模板</Button
            >
        </template>
    </div>
</template>
<script>
import { getTempInfpByID, templateAutomatic } from '../../api/proTemplate.js';
import { getDictInfoByName } from '@/api/dict.js'
import { mapState, mapActions } from 'vuex';
import WarningTip from '@/components/common/warning-tip';
import { imageFloverMixin } from '../../mixin/research';
export default {
    name: 'GenerateTemplate',
    // props:['needJupyter'],
    components: { WarningTip },
    mixins: [imageFloverMixin],
    data() {
        return {
            formData: { imageRef: '', flavorRef: '', count: 1 },
            rules: {
                imageRef: [
                    {
                        type: 'string',
                        required: true,
                        trigger: 'blur,change',
                    },
                ],
                flavorRef: [
                    {
                        type: 'string',
                        required: true,
                        trigger: 'blur,change',
                    },
                ],
                count: [
                    {
                        type: 'number',
                        required: true,
                        min: 1,
                        max: 3,
                        trigger: 'blur,change',
                    },
                ],
            },
            // imageList: [],
            // flavorList: [],
            selectImageList: [],
            current: {
                image: {},
                flavor: {},
            },
            needJupyter:false,
            jupyterImageId:'',
            dataLoading:false
        };
    },
    computed: {
        count() {
            let count = this.selectImageList.reduce((pre, cur, index) => {
                return pre + cur.count;
            }, 0);
            return count;
        },
        showFlavorList() {
            return this.getAvaiFlavorList(this.current.image);
            // if (!this.current.image.minRam) {
            //     return this.flavorList;
            // }
            // return this.flavorList.filter(
            //     (item) =>
            //         item.ram > Number(this.current.image.minRam) &&
            //         item.disk > Number(this.current.image.minDisk)
            // );
        }
    },
    watch:{
        needJupyter(val){
            this.initSelectImageList();
        }
    },
    created(){
        this.dataLoading = true;
        Promise.all([this.getImageList(),this.getFlavorList()]).then(data => {
            this.getDictInfoByName();
            this.dataLoading = false;
        })
    },
    mounted() {
        
    },
    methods: {
        addImage() {
            this.$refs['form']
                .validate((valid) => {
                    if (valid) {
                        if (this.count + this.formData.count > 3) {
                            this.$Message.warning('最多可创建三个镜像');
                            return;
                        }
                        let imageName = this.current.image.imageName;
                        let flavorName = this.current.flavor.flavorName;
                        let item = Object.assign({}, this.formData, {
                            imageName,
                            flavorName,
                        });
                        this.selectImageList.push(item);
                    } else {
                    }
                })
                .catch((error) => {});
        },
        delImage(index) {
            this.selectImageList.splice(index, 1);
        },
        addImageList() {},
        changeImage(id) {
            if (!id) {
                return;
            }
            this.current.image = this.imageList.find((item) => item.id === id);
            this.formData.flavorRef = '';
            // this.flavorList = this.showFlavorList.filter(
            //     (item) =>
            //         item.ram > Number(this.current.image.minRam) &&
            //         item.disk > Number(this.current.image.minDisk)
            // );
        },
        changeFlavor(id) {
            this.current.flavor = this.flavorList.find((item) => item.id === id);
        },
        templateAutomatic() {
            if (this.selectImageList.length > 3) {
                this.$Message.warning('最多可选择三个镜像生成模板，请删除多余镜像');
                return;
            }
            let data = [];
            this.selectImageList.forEach((item) => {
                let { imageRef, flavorRef } = item;
                for (let i = 0; i < item.count; i++) {
                    data.push({
                        imageRef,
                        flavorRef,
                    });
                }
            });
            templateAutomatic(data).then(({ code, data, message }) => {
                if (code === 1) {
                    let templateId = data;
                    this.querytempByID(templateId);
                } else {
                    this.$Message.error(message);
                }
            });
        },
        querytempByID(id) {
            getTempInfpByID(id)
                .then(({ code, data, message }) => {
                    if (code === 1) {
                        this.selectImageList = [];
                        // this.formData = { imageRef: '', flavorRef: '', count: 1 };
                        this.$refs['form'].resetFields();
                        this.$emit('on-success', {
                            id: id,
                            name: data.name,
                        });
                    }
                })
                .catch((err) => {
                    console.log(err);
                });
        },
        getAllImage() {
            let obj = {};
            let search = {
                pageIndex: 1,
                pageSize: 9999,
            };
            getallImage(obj, search).then((data) => {
                if (data.code === 1) {
                    this.imageList = data.data.items;
                    this.selectImageList = [];
                }
            });
        },
        getAllFlavor() {
            const search = {
                pageIndex: 1,
                pageSize: 9999,
            };
            getallFlavor(search).then((data) => {
                if (data.code === 1) {
                    let flavorList = data.data.items;
                    // flavorList = flavorList.filter(
                    //     (item) => item.cpu <= 4 && item.disk <= 80 && item.ram <= 8192
                    // );
                    this.flavorList = flavorList;
                    this.flavorListCopy = flavorList;
                }
            });
        },
        getDictInfoByName(){
            return new Promise((resolve,reject) => {
                getDictInfoByName({name:'searchJupyterImage'}).then(({code,attribute:data,message}) => {
                    if(code === 1){
                        this.jupyterImageId = data.data.value;
                        if(this.jupyterImageId){
                            let image = this.imageList.find(item => item.id === this.jupyterImageId);
                            if(image){
                                this.needJupyter = true
                            }else{
                                this.jupyterImageId = ''
                            }
                        }
                        // this.initSelectImageList()
                        resolve(data.data.value)
                    }else{
                        resolve()
                    }
                }).catch(error => {
                    resolve()
                })
            })
        },
        initSelectImageList(){
            if(this.needJupyter && this.jupyterImageId){
                let image = this.imageList.find(item => item.id === this.jupyterImageId);
                let flavor = this.getAvaiFlavorList(image)[0];
                this.selectImageList.unshift({
                    imageRef: image.id, 
                    flavorRef: flavor.id, 
                    count: 1 ,
                    imageName:image.imageName,
                    flavorName:flavor.flavorName
                })
            }else{
                if(this.selectImageList.length > 0){
                    this.selectImageList.splice(this.selectImageList.findIndex(item => item.imageRef === this.jupyterImageId),1)
                }
            }
        }
    },
};
</script>
<style scoped>
.flex {
    display: flex;
}
.flex-between {
    display: flex;
    justify-content: space-between;
}
.w100 {
    width: 100px;
}
.no-radius {
    border-radius: 0;
}
.generate-image-wrapper {
    padding: 4px 6px;
    /* background: var(--arrow-step-bgcolor); */
    background: #efefef;
}
.generate-image-wrapper /deep/ .ivu-form .ivu-form-item-label {
    display: none;
}
.generate-image-wrapper /deep/ .ivu-form-item .ivu-form-item {
    margin-right: 0;
}
.ivu-form-item {
    margin-bottom: 0;
}
.image-wrapper {
    margin: 10px 0;
}
.image-item {
    display: flex;
}
.image-item > span {
    flex: 1;
    padding: 0 4px;
    text-align: center;
    /* border-bottom: 1px solid var(--table-border); */
    color: var(--table-tr-color);
    /* border-bottom: var(--divider-color);
    color: var(--default-color); */
}
.image-item > span:not(:last-child) {
    margin-right: 2px;
}
.image-item.header > span {
    background: var(--image-table-th-bgcolor);
    color: var(--table-th-color);
}
.warn-tip {
    color: #f90;
    word-break: break-all;
}
</style>
